#include "Protocols/ShowableItem.h"
#include "protocols/Http.h"
#include "utilities/ReadablePacket.h"
#include "protocols/ProtocalCode.h"
#include "protocols/ProtocalPool.h"
#include "utilities/utilities.h"
#include <QtCore/QStringList>

REGISTER_PROTOCOL(Http)

using boost::shared_ptr;

void HttpHeader::toShowableItems(ShowableItem* root) const{
	QString* str = new QString((const char *)mData);
	QStringList Lines;
	QStringList Items;
	int pos = mPos,i = 1;
	ShowableItem* tmp,* flag;

	ShowableItem* proto = createProtocalItem("Hypertext Transfer Protocol",pos,getHeaderLength());
	root->pushChild(proto);

	Lines = str->split("\r\n");

	flag = createItemUnchange(Lines[0],"","",pos,Lines[0].size(),ShowableItem::ITEMICON_FIELD);
	proto->pushChild(flag);

	Items = Lines[0].split(" ");
	
	tmp = createItem(Items[0],"",pos,Items[0].size());
	flag->pushChild(tmp);

	pos++;
	tmp = createItem(Items[1],"",pos,Items[1].size());
	flag->pushChild(tmp);
	
	pos++;
	if (Items.count()==4&&!Items[3].isEmpty())
	{
		Items[2] = Items[2]+" "+Items[3];
	}
	tmp = createItem(Items[2],"",pos,Items[2].size());
	flag->pushChild(tmp);
	pos += 2;
	while (Lines[i] != "")
	{
		tmp = createItem(Lines[i],"",pos,Lines[i].size());
		proto->pushChild(tmp);

		pos += 2;
		i++;
	}
} 

QString HttpHeader::getSummary() const{
	QString* str = new QString((const char *)mData);
	QStringList Lines;
	
	Lines = str->split("\r\n");
	return Lines[0];
}

int HttpHeader::getHeaderLength() const{
	return mLength;
}
Http::Http():Protocol(HTTP,QString("HTTP"))
{
	shared_ptr<AppProtocolProperty> prop = make_shared<AppProtocolProperty>();
	prop->mDefaultPort.push_back(80);
	mInfo = prop;
}

boost::shared_ptr<PacketHeader> 
Http::analyzeProc(shared_ptr<ReadablePacket> packet,int low,int high,shared_ptr<Protocol>& tip)
{
	shared_ptr<HttpHeader> header(new HttpHeader(PROTOCOL_POINTER(Http),packet->getData(),low,high - low + 1));
		tip.reset();
	
	return header;
}